package com.stone.scan;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>Created with IntelliJ IDEA. </p>
 * <p>User: Stony </p>
 * <p>Date: 2016/7/1 </p>
 * <p>Time: 11:31 </p>
 * <p>Version: 1.0 </p>
 */
public class OptimizerAnnotationRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor,Ordered {

    private String basePackage;
    public static final String OPTIMIZER_BEAN_LIST = "G_OPTIMIZER_BEAN_LIST";
    private List<Class> classes;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        OptimizerScanner optimizerScanner = new OptimizerScanner(registry);
        try {
            classes = optimizerScanner.scanBeanClass(StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if(classes != null) {
            beanFactory.registerSingleton(OPTIMIZER_BEAN_LIST, classes);
        }else{
            beanFactory.registerSingleton(OPTIMIZER_BEAN_LIST, Collections.EMPTY_LIST);
        }
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 10;
    }
}
